<template>
  <a-space direction="vertical" size="large">
    <a-table :columns="columns" :data="dataList" :pagination="false">
      <template #tags="{ record }">
        <a-space wrap>
          <a-tag v-for="(tag, index) of record.tags" :key="index" color="blue"
            >{{ tag }}
          </a-tag>
        </a-space>
      </template>
      <template #acceptedRate="{ record }">
        {{ calculateAcceptedRate(record) }}
      </template>
      <template #createTime="{ record }">
        {{
          record.createTime
            ? moment(record.createTime).format("YYYY-MM-DD")
            : "-"
        }}
      </template>
      <template #optional="{ record }">
        <a-space>
          <a-button type="primary" @click="doQuestionPage(record)">
            开始
          </a-button>
        </a-space>
      </template>
    </a-table>
  </a-space>
</template>

<script setup lang="ts">
import moment from "moment/moment";
import { onMounted, ref, watchEffect } from "vue";
import { useRouter } from "vue-router";
import {
  Question,
  QuestionControllerService,
  QuestionQueryRequest,
} from "../../../generated";
import message from "@arco-design/web-vue/es/message";

const columns = [
  {
    title: "题号",
    dataIndex: "id",
  },
  {
    title: "题目名称",
    dataIndex: "title",
  },
  {
    title: "通过率(通过数/提交数)",
    slotName: "acceptedRate",
  },
  {
    title: "创建时间",
    slotName: "createTime",
  },
  {
    title: "操作",
    slotName: "optional",
  },
];

const dataList = ref([]);

const router = useRouter();

const total = ref(0);

const doQuestionPage = (question: Question) => {
  router.push({
    path: `/view/question/${question.id}`,
  });
};

/**
 * 计算通过率
 * @param record 题目记录
 * @returns 格式化的通过率字符串
 */
const calculateAcceptedRate = (record: any): string => {
  const submitNum = record.submitNum || 0; // 提交次数，默认为 0
  const acceptedNum = record.acceptedNum || 0; // 通过次数，默认为 0

  // 如果提交次数为 0，则通过率为 0%
  if (submitNum === 0) {
    return `0% (${acceptedNum}/${submitNum})`;
  }

  // 计算通过率并保留两位小数
  const rate = (acceptedNum / submitNum) * 100;

  // 返回格式化的字符串
  return `${rate}% (${acceptedNum}/${submitNum})`;
};
const searchParams = ref<QuestionQueryRequest>({
  title: "",
  tags: [],
  pageSize: 8,
  current: 1,
  sortField: "submitNum",
  sortOrder: "descend",
});

const loadData = async () => {
  const res = await QuestionControllerService.listQuestionByPageUsingPost(
    searchParams.value
  );
  if (res.code === 0) {
    dataList.value = res.data.records;
    total.value = res.data.total;
  } else {
    message.error("加载失败，" + res.message);
  }
};

/**
 * 监听 searchParams 变量，改变时触发页面的重新加载
 */
let timer;
watchEffect(() => {
  if (timer) clearTimeout(timer);
  timer = setTimeout(() => {
    loadData();
  }, 300); // 延迟 300ms 执行
});
/**
 *页面加载时,请求数据
 */
onMounted(() => {
  loadData();
});
</script>

<style scoped></style>
